package ro.mfl.sockets.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Hashtable;
import java.util.Map;


public class Server {

    private ServerSocket serverSocket;
    private Map<String, ServerReadThread> clientMap;
    private static Server serverInstance;

    private Server() {
        try {
            clientMap = new Hashtable<String, ServerReadThread>();
            serverSocket = new ServerSocket(9999);
        }
        catch (IOException ex) {
            System.out.println("ERROR creating server socket");
        }
    }

    public static Server getInstance() {
        if(serverInstance == null)
            serverInstance = new Server();
        return serverInstance;
    }

    public void start() throws Exception {
        while(true) {
            Socket clientSocket = serverSocket.accept();
            System.out.println("new connection");
            BufferedReader reader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            String clientMessage = reader.readLine();
            System.out.println("Client: " + clientMessage);
            int clientNumber = clientMap.size();
            ServerReadThread readThread = new ServerReadThread(clientSocket);
            clientMap.put(clientMessage + "-" + clientNumber, readThread);
            readThread.start();
            readThread.join();
        }
    }

    public static void main(String[] args) {
        try {
            Server server = Server.getInstance();
            server.start();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
}

class ServerReadThread extends Thread {

    private Socket socket;

    ServerReadThread(Socket clientSocket) {
        socket = clientSocket;
    }

    public void run() {
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));

            while(true) {
                String line = reader.readLine();
                System.out.println(line);
            }
        }
        catch(Exception e) {
            e.printStackTrace();
        }
    }
}